const wxpay = require('../../utils/pay.js')
const app = getApp()
import {
  getOrders,
  getPayParam,
  refund,
  removeOrder,
  receiving
} from '../../api/order.js'
Page({
  data: {
    statusType: ["待付款", "待发货", "待收货", "已完成"],
    currentType: 0,
    tabClass: ["", "", "", "", ""],
    bodyHeight: null,
    index: 1,
    isFinish: false,
    orderList: [],
    selectIndex: 0,
    reason: '不想要了',
    refundBox: false,
    refundOrder: null,
    refundOptions: [{
        value: '不想要了',
        name: '不想要了',
        checked: 'true'
      },
      {
        value: '地址信息填写错误',
        name: '地址信息填写错误'
      },
      {
        value: '商品错选/多选 (规格、数量等)',
        name: '商品错选/多选 (规格、数量等)'
      },
      {
        value: '商品降价',
        name: '商品降价'
      },
      {
        value: '没用/少用/错用优惠',
        name: '没用/少用/错用优惠'
      },
      {
        value: '发货时间过长',
        name: '发货时间过长'
      },
      {
        value: '商品无货',
        name: '商品无货'
      },
      {
        value: '其他',
        name: '其他'
      },
    ],
    refundInput: false,
    status: {
      'UNPAID': '等待买家付款',
      'PAID': '等待卖家发货',
      'UNDELIVERED': '等待卖家发货',
      'DELIVERED': '卖家已发货',
      'COMPLETED': '已完成'
    },
  },
  radioChange(e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    if (e.detail.value == '其他') {
      this.setData({
        reason: '',
        refundInput: true,
      })
    } else {
      this.setData({
        refundInput: false,
        reason: e.detail.value
      })
    }
    // const items = this.data.refundOptions
    // for (let i = 0, len = items.length; i < len; ++i) {
    //   items[i].checked = items[i].value === e.detail.value
    // }

    // this.setData({
    //   items
    // })
  },
  statusTap(e) {
    if (e && e.hasOwnProperty("currentTarget")) {
      if (e.currentTarget.dataset.text == '售后') {
        this.setData({
          currentType: 4
        });
      } else {
        this.setData({
          currentType: e.currentTarget.dataset.index
        });
      }
    } else {
      this.setData({
        currentType: e.currentType
      });
    }

    this.setData({
      orderList: [],
      isFinish: false,
      index: 1,
    })
    this.getData()
    // this.onShow()
  },
  deleteOrder(e) {
    let that = this
    var OrderId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '确定要删除该订单吗？',
      content: '',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '加载中...',
            mask: true
          });
          app.postForm('order/delete_order', {
            OrderId
          }, res => {
            if (res && res.code == "0") {
              wx.hideLoading()
              wx.showToast({
                title: '删除成功'
              })
              that.statusTap({
                currentType: that.data.currentType
              })
            } else {
              wx.hideLoading()
              wx.showToast({
                title: res.msg,
                icon: 'none'
              })
            }
          })
        }
      }
    })
  },
  orderDetail: function (e) {
    var orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: "/pages/order-detail/order-detail?id=" + orderId + '&share=1'
    })
  },
  goComment(e){
    let it = e.currentTarget.dataset.item
    console.log(it)
    wx.navigateTo({
      url: `/pages/comment/comment?goodsId=${it.goodsId}&skuId=${it.skuId}&orderItemSn=${it.sn}&name=${it.name}&img=${it.image}`,
    })
  },
  async cancelOrderTap(e) {
    let that = this;
    let orderId = e.currentTarget.dataset.id
    let list = that.data.orderList
    this.setData({
      refundBox: true
    })
    // wx.showModal({
    //   title: '确定要取消该订单吗？',
    //   content: '',
    //   async success(res) {
    //     if (res.confirm) {
    //       wx.showLoading({
    //         title: '加载中...',
    //         mask: true
    //       })
    //       let res = await removeOrder(orderId, wx.getStorageSync('access_token'))
    //       wx.hideLoading()
    //       if (res && res.code == 10000) {
    //         for(let i = 0; i < list.length; i++){
    //           if(list[i].sn == orderId) {
    //             list = list.splice(i, 1)
    //           }
    //         }
    //         this.setData({
    //           orderLisr: list
    //         })
    //         wx.showToast({
    //           title: '已取消',
    //         })
    //       }
    //       // app.postForm("/order/cancel_order", {
    //       //   CustId: app.globalData.uid,
    //       //   OrderId: orderId
    //       // }, res => {
    //       //   wx.hideLoading();
    //       //   if (res && res.code == "0") {
    //       //     that.statusTap({
    //       //       currentType: 0
    //       //     });
    //       //   }
    //       // })
    //     }
    //   }
    // })
  },
  async toPayTap(e) {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    var that = this;
    if (e.currentTarget.dataset.type == 2) {
      wx.showToast({
        title: '财务正在核对支付状态，请等待',
        icon: 'none'
      })
      return
    }
    var orderId = e.currentTarget.dataset.id;
    let orderList = that.data.orderList
    that.setData({
      selectIndex: e.currentTarget.dataset.idx
    })
    orderList[that.data.selectIndex].Status = 99
    that.setData({
      orderList
    })
    let res = await getPayParam(orderId, wx.getStorageSync('access_token'))
    console.log(res)
    wx.hideLoading()
    that.wxPay(res.data)
  },
  wxPay(params) {
    let that = this
    console.log(params)
    let orderList = that.data.orderList
    wx.requestPayment({
      timeStamp: params.timeStamp,
      nonceStr: params.nonceStr,
      package: params.package,
      signType: params.signType,
      paySign: params.paySign,
      success: function (res) {
        wx.hideLoading();
        wx.showToast({
          title: '支付成功',
          icon: 'success'
        })
        orderList[that.data.selectIndex].Status = 1
        that.setData({
          orderList
        })
        that.statusTap({
          currentType: 0
        })
      },
      fail: function (res) {
        wx.hideLoading();
        wx.showToast({
          title: '已取消支付',
          icon: 'none'
        })
        orderList[that.data.selectIndex].Status = 0
        that.setData({
          orderList
        })
      },
      complete: function (res) {
        wx.hideLoading();
        console.log(res);
      }
    })
  },
  close() {
    this.setData({
      refundBox: false,
      refundOrder: null,
      reason: ''
    })
  },
  inputReason(e) {
    this.setData({
      reason: e.detail.value
    })
  },
  async selectTap(e) {
    var index = e.currentTarget.dataset.index
    var list = this.data.refundOrder.orderItems
    console.log(list[parseInt(index)])
    list[parseInt(index)].active = !list[parseInt(index)].active
    this.setData({
      refundOrder: this.data.refundOrder
    })
  },
  async jiaBtnTap(e) {
    var index = e.currentTarget.dataset.index
    var list = this.data.refundOrder.orderItems
    if (index !== "" && index != null) {
      if (list[parseInt(index)].number == list[parseInt(index)].num) {
        wx.showToast({
          title: '已达最大数量',
          icon: 'none'
        })
        return
      }
      list[parseInt(index)].number++
      this.setData({
        refundOrder: this.data.refundOrder
      })
    }
  },
  async jianBtnTap(e) {
    var index = e.currentTarget.dataset.index
    var list = this.data.refundOrder.orderItems
    if (index !== "" && index != null) {
      if (list[parseInt(index)].number > 1) {
        list[parseInt(index)].number--
        this.setData({
          refundOrder: this.data.refundOrder
        })
      }
    }
  },
  refund(e) {
    let refundOrder = e.currentTarget.dataset.item
    let status = e.currentTarget.dataset.status
    refundOrder.orderItems.forEach(item => {
      item.selectTap = false
      item.number = item.num
    })
    this.setData({
      refundBox: true,
      refundOrder,
      refundTitle: status == 1 ? '申请退款' : '取消订单'
    })
  },
  subRefund() {
    let that = this
    if (that.data.reason == '') {
      wx.showToast({
        title: '请输入退款原因',
        icon: 'none'
      })
      return
    }
    wx.showModal({
      title: '提醒',
      content: '确认要提交申请吗？',
      confirmColor: '#008B8B',
      async success(res) {
        wx.showLoading({
          title: '加载中...',
          mask: true
        })
        if (res.confirm) {
          console.log(that.data.refundOrder)
          if (that.data.refundTitle == '申请退款') {
            let res = await refund(that.data.refundOrder.sn, that.data.reason, wx.getStorageSync('access_token'))
            if (res && res.code == 10000) {
              for (let i = 0; i < that.data.orderList.length; i++) {
                if (that.data.orderList[i].sn == that.data.refundOrder.sn) {
                  that.data.orderList.splice(i, 1)
                }
              }
              that.setData({
                orderList: that.data.orderList
              })
              wx.showToast({
                title: '已提交申请',
                icon: 'success'
              })
              that.setData({
                refundBox: false,
                refundOrder: null
              })
            } else {
              wx.showToast({
                title: res.msg,
                icon: 'none'
              })
            }
          } else {
            wx.showLoading({
              title: '加载中...',
              mask: true
            })
            let res = await removeOrder(that.data.refundOrder.sn, that.data.reason, wx.getStorageSync('access_token'))
            wx.hideLoading()
            if (res && res.code == 10000) {
              for (let i = 0; i < that.data.orderList.length; i++) {
                if (that.data.orderList[i].sn == that.data.refundOrder.sn) {
                  that.data.orderList.splice(i, 1)
                }
              }
              that.setData({
                orderList: that.data.orderList
              })
              that.setData({
                refundBox: false,
                refundOrder: null
              })
              wx.showToast({
                title: '已取消',
              })
            }
          }

          // app.postForm('order/refund_order', postData, res => {
          //   console.log(res)
          //   wx.hideLoading()
          //   if (res.code == 0) {
          //     that.statusTap({
          //       currentType: 1
          //     });
          //     wx.showToast({
          //       title: res.msg,
          //     })
          //   } else {
          //     wx.showToast({
          //       title: res.msg,
          //       icon: 'error'
          //     })
          //   }
          // })
        } else {
          wx.hideLoading({
            success: (res) => {},
          })
        }
      }
    })
  },
  onLoad: function (e) {
    var that = this;
    var currentType = e.currentType
    wx.hideShareMenu()
    if (e && e.hasOwnProperty('share')) {
      console.log(1)
      if (e.share) {
        that.setData({
          share: e.share
        });
        currentType = e.currentType;
      }
    }
    if (app.globalData.iphone == true) {
      that.setData({
        iphone: 'iphone'
      })
    }
    if (currentType) {
      that.setData({
        currentType: currentType
      })
    }
    console.log(e)
    
  },
  onReady: function () {
    // 生命周期函数--监听页面初次渲染完成

  },
  getOrderStatistics: function () {
    var that = this;
    // wx.request({
    //   url: app.siteInfo.url + app.siteInfo.subDomain + '/order/statistics',
    //   data: { token: app.globalData.token },
    //   success: (res) => {
    //     wx.hideLoading();
    //     if (res.data.code == 0) {
    //       var tabClass = that.data.tabClass;
    //       if (res.data.data.count_id_no_pay > 0) {
    //         tabClass[0] = "red-dot"
    //       } else {
    //         tabClass[0] = ""
    //       }
    //       if (res.data.data.count_id_no_transfer > 0) {
    //         tabClass[1] = "red-dot"
    //       } else {
    //         tabClass[1] = ""
    //       }
    //       if (res.data.data.count_id_no_confirm > 0) {
    //         tabClass[2] = "red-dot"
    //       } else {
    //         tabClass[2] = ""
    //       }
    //       if (res.data.data.count_id_no_reputation > 0) {
    //         tabClass[3] = "red-dot"
    //       } else {
    //         tabClass[3] = ""
    //       }
    //       if (res.data.data.count_id_success > 0) {
    //         //tabClass[4] = "red-dot"
    //       } else {
    //         //tabClass[4] = ""
    //       }

    //       that.setData({
    //         tabClass: tabClass,
    //       });
    //     }
    //   }
    // })
  },
  toConfirmTap: function (e) {
    let that = this;
    let orderId = e.currentTarget.dataset.id;
    let formId = e.detail.formId;
    wx.showModal({
      title: '确认您已收到商品？',
      content: '',
      async success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '加载中...',
            mask: true
          })
          let res = await receiving(orderId, wx.getStorageSync('access_token'))
          console.log(res)
          wx.hideLoading()
          if (res && res.code == 10000) {
            that.statusTap({
              currentType: 2
            })
          } else {
            wx.showToast({
              title: '网路错误',
              icon: 'none'
            })
          }
        }
      }
    })
  },
  logisticsTap(e) {
    var orderId = e.currentTarget.dataset.id;
    if (orderId) {
      wx.navigateTo({
        url: '/pages/logistics/logistics?id=' + orderId,
      })
    } else {
      wx.showToast({
        title: '等待物流公司发货中',
        icon: 'none'
      })
      return
    }
  },
  toTel() {
    wx.makePhoneCall({
      phoneNumber: '13844241140',
    })
  },
  exit() {
    this.setData({
      refundBox: false
    })
  },
  onBeforeEnter(res) {},
  onEnter(res) {},
  onAfterEnter(res) {

  },
  onBeforeLeave(res) {},
  onLeave(res) {},
  onAfterLeave(res) {
    console.log('关了')
    this.setData({
      refundOptions: [{
          value: '不想要了',
          name: '不想要了',
          checked: 'true'
        },
        {
          value: '地址信息填写错误',
          name: '地址信息填写错误'
        },
        {
          value: '商品错选/多选 (规格、数量等)',
          name: '商品错选/多选 (规格、数量等)'
        },
        {
          value: '商品降价',
          name: '商品降价'
        },
        {
          value: '没用/少用/错用优惠',
          name: '没用/少用/错用优惠'
        },
        {
          value: '发货时间过长',
          name: '发货时间过长'
        },
        {
          value: '商品无货',
          name: '商品无货'
        },
        {
          value: '其他',
          name: '其他'
        },
      ],
      refundInput: false,
      reason: '不想要了'
    })
  },

  onClickOverlay(res) {

  },
  async getData() {
    let _this = this;
    if (this.data.isFinish) {
      return
    }
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    let status = this.data.currentType
    let res = await getOrders(this.data.index, Number(status), wx.getStorageSync('access_token'))
    wx.hideLoading()
    if (res && res.code == 10000) {
      if (res.data.records.length > 0) {
        res.data.records.forEach(item => {
          item.Status = status
        })
        _this.setData({
          orderList: _this.data.orderList.concat(res.data.records).filter(item => {
            return item.groupAfterSaleStatus.indexOf('NEW') > -1  || item.groupAfterSaleStatus.indexOf('NOT_APPLIED') > -1
          }),
          index: this.data.index + 1
        })
        console.log(this.data.orderList)
      } else {
        _this.setData({
          isFinish: true,
        })
      }
    }
    if (status == 4) {
      status = 's2'
    }
    // app.get(`order/get_orders?CustId=${app.globalData.uid}&Status=${status}&page=${this.data.index}&size=20&IsDealer=0`, (res) => {
    //   wx.hideLoading();
    //   if (res && res.code == "0") {
    //     if (res.result.length > 0) {
    //       _this.setData({
    //         orderList: _this.data.orderList.concat(res.result),
    //         index: this.data.index + 1
    //       });
    //     } else {
    //       _this.setData({
    //         isFinish: true,
    //       })
    //       // wx.showToast({
    //       //   title: '没有更多了~',
    //       // })
    //     }
    //   }
    // })
  },
  exit() {

  },
  onShow: function (e) {
    if (!wx.getStorageSync('access_token')) {
      wx.showModal({
        title: '请先登录',
        content: '',
        showCancel: false,
        success: (res) => {
          wx.navigateBack({
            delta: 1 //返回上一级页面
          })
        }
      })
      return
    }
    // 获取订单列表
    // wx.showLoading();
    var that = this;
    that.statusTap({
      currentType: that.data.currentType
    })
    // this.getOrderStatistics();

    // wx.request({
    //   url: app.siteInfo.url + app.siteInfo.subDomain + '/order/list',
    //   data: postData,
    //   success: (res) => {
    // 		console.log(res)
    //     wx.hideLoading();
    //     if (res.data.code == 0) {
    //       that.setData({
    //         orderList: res.data.data.orderList,
    //         logisticsMap: res.data.data.logisticsMap,
    //         goodsMap: res.data.data.goodsMap
    //       });
    //     } else {
    //       this.setData({
    //         orderList: null,
    //         logisticsMap: {},
    //         goodsMap: {}
    //       });
    //     }
    //   }
    // })
    // var winInfo = wx.getSystemInfo({
    // 	success: function (res) {
    // 		var windowHeight = res.windowHeight;
    // 		var statusBarHeight = res.statusBarHeight;
    // 		var titleBarHeight = 0
    // 		if (res.model.indexOf('iPhone') !== -1) {
    // 			titleBarHeight = 44
    // 		} else {
    // 			titleBarHeight = 48
    // 		}
    // 		var query = wx.createSelectorQuery();
    // 		query.select('.status-box').boundingClientRect()
    // 		query.exec((res) => {
    // 		  var listHeight = res[0].height; // 获取list高度
    // 			that.setData({ bodyHeight: windowHeight - statusBarHeight - titleBarHeight - listHeight });
    // 		})


    // 	}
    // });
  },
  onHide: function () {
    // 生命周期函数--监听页面隐藏

  },
  onUnload: function () {
    // 生命周期函数--监听页面卸载

  },
  onPullDownRefresh: function () {
    // 页面相关事件处理函数--监听用户下拉动作

  },
  onReachBottom: function () {
    // 页面上拉触底事件的处理函数

  }
})